package com.cx.base.day19_thread;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author: robert.song
 * @Date: Created in 2022/5/7
 */

public class Thread_20_1_ThreadLocal {
    public static void main(String[] args) {
        UseThreadLocal test = new UseThreadLocal();
        test.startThreadArrya();
    }
}

@Slf4j
class UseThreadLocal {

    //每个线程的threadLocalMap都会存储一个key为threadLocal1的entry
    ThreadLocal<String> threadLocal1 = new ThreadLocal();

    //只有循环指定的线程的threadLocalMap会存储一个key为threadLocal2的entry
    ThreadLocal<Integer> threadLocal2 = new ThreadLocal();

    public void startThreadArrya() {
        Thread[] runs = new Thread[3];
        for (int i = 0; i < runs.length; i++) {
            new TestThread(i).start();
        }
    }

    class TestThread extends Thread {

        private final int i;

        public TestThread(int i) {
            this.i = i;
        }

        @Override
        public void run() {
            String threadName = Thread.currentThread().getName();
            threadLocal1.set(threadName);
            log.debug("threadLocal1的地址: {}", threadLocal1);
            log.debug("testThread" + this.i + "的key: {},value: {}", threadLocal1, threadLocal1.get());
            if (this.i == 2) {
                threadLocal2.set(i);
                log.debug("threadLocal2的地址: {}", threadLocal2);
                log.debug("testThread" + this.i + "的key: {},value: {}", threadLocal2, threadLocal2.get());
            }

        }
    }
}